<template>
    <div :class="`login-container ` + TARO_ENV">
        <!-- 登录界面 -->
        <!-- 微信 -->
        <div class="container-inner flex-column-center" v-if="TARO_ENV === 'weapp'">
            <nut-avatar size="large">
                <img :src="state.avatarUrl" />
            </nut-avatar>
            <nut-button type="info" @click="registerAndLogin">微信一键登录</nut-button>
        </div>
        <!-- h5 -->
        <div class="container-inner flex-column-center" v-else-if="TARO_ENV === 'h5'">
            <nut-form ref="formRef" :rules="rules" :model-value="form">
                <div class="center flex-column-center">
                    <img :src="LOGO" />
                    <nut-form-item prop="email" :show-error-line="false">
                        <nut-input v-model="form.email" type="email" placeholder="请输入邮箱" />
                    </nut-form-item>
                    <nut-form-item v-if="state.register" prop="verificationCode" :show-error-line="false">
                        <nut-input placeholder="请输入验证码" v-model="form.verificationCode">
                            <template v-if="state.register" #right>
                                <nut-button type="info" size="small" :disabled="state.countdown" @click="getVerificationCode">
                                    {{ [0, 60].includes(state.countdown) ? '获取验证码' : state.countdown }}
                                </nut-button>
                            </template>
                        </nut-input>
                    </nut-form-item>
                    <nut-form-item prop="password" :show-error-line="false">
                        <nut-input placeholder="请输入密码" v-model="form.password" type="password" />
                    </nut-form-item>
                    <nut-button class="login-button" type="info" @click="loginOrRegister">
                        {{ state.register ? '注册' : '登录' }}
                    </nut-button>
                </div>
                <div class="footer">
                    <span class="register" @click="state.register = !state.register">
                        {{ state.register ? '返回登陆' : '立即注册' }}
                    </span>
                </div>
            </nut-form>
        </div>
        <Notify ref="notifyRef" />
        <Loading v-model:visible="state.loading" />
    </div>
</template>

<script lang="ts">
export default { name: '' }
</script>

<script lang="ts" setup>
import { reactive, ref, nextTick, onMounted, useAttrs, useSlots } from 'vue'
import { Form } from '@nutui/nutui-taro'
import Taro from '@tarojs/taro'
import Notify from '@/components/system/Notify.vue'
import Loading from '@/components/system/Loading.vue'
import { $http } from '@/request'
import LOGO from '@/assets/images/logo.jpg'

Taro.removeStorageSync('token')
const TARO_ENV = process.env.TARO_ENV
const notifyRef = ref<InstanceType<typeof Notify>>()
const formRef = ref<InstanceType<typeof Form>>()
const rules = {
    email: [
        { required: true, message: '请输入邮箱' },
        { regex: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, message: '请输入正确的邮箱' }
    ],
    verificationCode: [
        { required: true, message: '请输入验证码' },
        { regex: /^\d{6}$/, message: '请输入6位纯数字验证码' }
    ],
    password: [
        { required: true, message: '请输入密码' },
        { regex: /^.{6,}$/, message: '密码长度至少为6位' }
    ]
}

const state = reactive({
    loading: false,
    avatarUrl: '',
    name: '',
    register: false,
    countdown: 0
})

const form = reactive({
    email: '',
    verificationCode: '',
    password: ''
})

const weappLogin = () => {
    state.loading = true
    let params = {}
    Taro.getUserInfo().then(r => {
        console.log('UserInfo', r)
        state.avatarUrl = r.userInfo.avatarUrl ?? ''
        state.name = r.userInfo.nickName ?? ''
    }).catch(e => { })
    // 获取wxCode
    Taro.login().then(r => {
        params = {
            wxCode: r.code
        }
        return $http.login(params)
    }).then(r => {
        loginSuccess(r.data.data.token)
    }).catch(e  => {
        state.loading = false
    })
}

const registerAndLogin = () => {
    state.loading = true
    Taro.login().then(r => {
        return $http.register({ wxCode: r.code, name: state.name })
    }).then(r => {
        notifyRef.value?.$success('注册成功')
        loginSuccess(r.data.data.token)
    }).catch(e => {
        if (e.data.code === 403) return weappLogin()
        notifyRef.value?.$error('注册失败')
        state.loading = false
    })
}

const loginSuccess = (token: string) => {
    state.loading = true
    Taro.setStorageSync('token', token)
    $http.getUserInfo().then(r => {
        Taro.switchTab({
            url: '/pages/home/index'
        })
    }).catch((e: any) => {
        notifyRef.value?.$error('获取用户信息失败')
        state.loading = false
    })
}

const getVerificationCode = () => {
    state.loading = true
    $http.getVerificationCode({ email: form.email }).then(() => {
        notifyRef.value?.$success('验证码发送成功')
        state.countdown = 60
        const interval = setInterval(() => {
            state.countdown--
            if (state.countdown === 0) clearInterval(interval)
        }, 1000)
    }).catch(e => {
        notifyRef.value?.$error(e.data?.message ?? '验证码发送失败')
    }).finally(() => {
        state.loading = false
    })
}

const loginOrRegister = () => {
    formRef.value?.validate().then(({ valid }) => {
        if (!valid) return
        state.loading = true
        if (state.register) {
            $http.register(form).then(r => {
                form.verificationCode = ''
                state.register = false
                loginOrRegister()
            }).catch(e => {
                notifyRef.value?.$error(e.data?.message ?? '注册失败')
            }).finally(() => {
                state.loading = false
            })
        } else {
            $http.login(form).then(r => {
                loginSuccess(r.data.data.token)
            }).catch(e => {
                notifyRef.value?.$error(e.data?.message ?? '登录失败')
            }).finally(() => {
                state.loading = false
            })
        }
    })

}

if (process.env.TARO_ENV === 'weapp') {
    weappLogin()
}

// defineExpose({

// })
</script>
<style lang="scss">
.login-container {
    width: 100%;
    &.weapp {
        display: flex;
        justify-content: center;
        align-items: center;
        .container-inner {
            .nut-avatar {
                margin-bottom: 40px;
            }
        }
    }
    &.h5 {
        .container-inner {
            .nut-form {
                .nut-cell-group__wrap {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    box-shadow: none;
                    .center {
                        img {
                            margin: 200px 0 60px 0;
                            width: 80%;
                        }
                        .login-button {
                            margin-top: 50px;
                            width: 90%;
                        }
                    }
                }
            }
            .footer {
                margin-top: 60px;
                .register {
                    color: #4987f2;
                    font-weight: bolder;
                    font-size: 30px;
                    user-select: none;
                    &:active {
                        opacity: 0.6;
                    }
                }
            }
        }
    }
}
</style>